<template>
  <div class="activity-list-container">
    <h2 class="page-title">活动管理</h2>
    
    <!-- 操作栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" icon="Plus" @click="$router.push('/activity/create')">
            新增活动
          </el-button>
          <el-button icon="Refresh" @click="loadActivityList">刷新</el-button>
        </el-col>
        <el-col :span="18">
          <el-space wrap>
            <el-select v-model="filters.type" placeholder="活动类型" clearable style="width: 120px" @change="loadActivityList">
              <el-option label="全部" :value="undefined" />
              <el-option label="线上" :value="1" />
              <el-option label="线下" :value="2" />
            </el-select>
            
            <el-select v-model="filters.status" placeholder="活动状态" clearable style="width: 120px" @change="loadActivityList">
              <el-option label="全部" :value="undefined" />
              <el-option label="未开始" :value="1" />
              <el-option label="进行中" :value="2" />
              <el-option label="已结束" :value="3" />
            </el-select>
            
            <el-input
              v-model="filters.keyword"
              placeholder="搜索活动名称"
              clearable
              style="width: 200px"
              @clear="loadActivityList"
              @keyup.enter="loadActivityList"
            >
              <template #append>
                <el-button icon="Search" @click="loadActivityList" />
              </template>
            </el-input>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 活动列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="activityList"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column prop="coverImage" label="封面" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.coverImage"
              fit="cover"
              class="cover-image"
              :preview-src-list="[row.coverImage]"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="活动名称" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 1 ? 'success' : 'primary'" size="small">
              {{ row.type === 1 ? '线上' : '线下' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="类别" width="100" />
        
        <el-table-column prop="location" label="地点" min-width="120" show-overflow-tooltip />
        
        <el-table-column label="报名人数" width="100">
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.actualParticipants >= row.maxParticipants }">
              {{ row.actualParticipants || 0 }} / {{ row.maxParticipants }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="price" label="费用" width="80">
          <template #default="{ row }">
            {{ row.price > 0 ? `¥${row.price}` : '免费' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="isHot" label="热门" width="60">
          <template #default="{ row }">
            <el-switch
              v-model="row.isHot"
              @change="handleHotChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="180" />
        
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              icon="View"
              @click="handleViewRegistrations(row)"
            >
              报名
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="Edit"
              @click="$router.push(`/activity/edit/${row.id}`)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadActivityList"
          @current-change="loadActivityList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activityList = ref([])

const filters = reactive({
  type: null,
  status: null,
  keyword: ''
})

// 加载活动列表
const loadActivityList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.ACTIVITY_LIST, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        type: filters.type,
        status: filters.status,
        keyword: filters.keyword
      }
    })
    
    if (response.code === 200) {
      activityList.value = response.data.list || response.data || []
      total.value = response.data.total || activityList.value.length
    }
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = { 1: '未开始', 2: '进行中', 3: '已结束' }
  return texts[status] || '未知'
}

// 获取状态颜色
const getStatusType = (status) => {
  const types = { 1: 'info', 2: 'success', 3: '' }
  return types[status] || ''
}

// 查看报名情况
const handleViewRegistrations = (row) => {
  router.push(`/activity/registrations/${row.id}`)
}

// 切换热门状态
const handleHotChange = async (row) => {
  try {
    const response = await request.put(`${API_ENDPOINTS.ACTIVITY_UPDATE}/${row.id}`, {
      isHot: row.isHot
    })
    
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      row.isHot = !row.isHot
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    row.isHot = !row.isHot
  }
}

// 删除活动
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个活动吗？删除后将无法恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`${API_ENDPOINTS.ACTIVITY_DELETE}/${row.id}`)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadActivityList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

onMounted(() => {
  loadActivityList()
})
</script>

<style scoped>
.activity-list-container {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.toolbar-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

.cover-image {
  width: 90px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>

